﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using PepsiCo.Common;
using Microsoft.SharePoint.Administration;
using T2V.SharePoint.Common.Utilities.Camlex;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace PepsiCo.Intranet.WebParts.ModernUI
{
    public partial class ModernUIUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadModernUI();
        }

        protected void LoadModernUI()
        {
            try
            {
                StringBuilder htmlBuilder = new StringBuilder();

                SPWeb spWeb = SPContext.Current.Web;

                SPList splistModernUI = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.Tile.LIST_URL);

                if (splistModernUI != null)
                {
                    string caml = string.Empty;
                    var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();

                    expressionsAnd.Add(x => ((bool)x[PepsiCoConstants.Tile.IS_ACTIVE_COLUMN]) == true);

                    caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x[PepsiCoConstants.Tile.ITEM_ORDER_COLUMN] as Camlex.Asc).ToString();

                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;

                    SPListItemCollection items = splistModernUI.GetItems(spQuery);

                    if (items != null && items.Count > 0)
                    {
                        foreach(SPListItem item in items)
                        {
                            string tileContentType = item[PepsiCoColumnId.Tile.TileContentType].ToString();

                            switch (tileContentType)
                            {
                                case "Banner":
                                    htmlBuilder.Append(RenderBanners(spWeb, item));
                                    break;
                                case "News":
                                    htmlBuilder.Append(RenderNews(spWeb, item));
                                    break;
                                case "Contacts":
                                    htmlBuilder.Append(RenderContacts(spWeb, item));
                                    break;
                                case "Services and tools":
                                    htmlBuilder.Append(RenderServicesAndTools(spWeb, item));
                                    break;
                                case "Custom":
                                    htmlBuilder.Append(RenderCustomContent(spWeb, item));
                                    break;
                            }
                        }
                    }
                }

                ltModernUI.Text = htmlBuilder.ToString();
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
            
        }

        protected string RenderBanners(SPWeb spWeb, SPListItem itemTile)
        {
            StringBuilder htmlBuilder = new StringBuilder();

            try
            {

                string tileWideSpell = itemTile[PepsiCoColumnId.Tile.TileWide].ToString();
                string tileTallSpell = itemTile[PepsiCoColumnId.Tile.TileTall].ToString();

                string tileWidth = CalculateTileWideOrTall(tileWideSpell);
                string tileHeight = CalculateTileWideOrTall(tileTallSpell);

                string tileColor = itemTile[PepsiCoColumnId.Tile.TileColor].ToString();

                string dataSpeed = itemTile[PepsiCoColumnId.Tile.DataSpeed].ToString();
                string dataDelay = itemTile[PepsiCoColumnId.Tile.DataDelay].ToString();
                //string dataPauseOnHover = itemTile[PepsiCoColumnId.Tile.DataPauseOnHover].ToString();
                string dataDirection = itemTile[PepsiCoColumnId.Tile.DataDirection].ToString() == "horizontal" ? "1" : "2";

                string dataSource = itemTile[PepsiCoColumnId.Tile.DataSource].ToString().Split(new string[] { ";#" }, StringSplitOptions.None)[0];

                SPList splistBanners;
                if (dataSource.IndexOf("/") == -1)
                {
                    Guid dataSourceGuid = new Guid(dataSource);
                    splistBanners = spWeb.Lists[dataSourceGuid];
                }
                else
                {
                    splistBanners = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + dataSource);
                }
                

                StringBuilder htmlBuilderBanners = new StringBuilder();

                //SPList splistBanners = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.Banner.LIST_URL);
                //SPList splistBanners = spWeb.Lists[dataSourceGuid];

                if (splistBanners != null)
                {
                    string caml = string.Empty;
                    var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();

                    expressionsAnd.Add(x => ((bool)x[PepsiCoConstants.Banner.IS_ACTIVE_COLUMN]) == true);

                    caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x[PepsiCoConstants.Banner.ITEM_ORDER_COLUMN] as Camlex.Asc).ToString();

                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;

                    SPListItemCollection banners = splistBanners.GetItems(spQuery);

                    if (banners != null && banners.Count > 0)
                    {
                        string bannerListURL = spWeb.ServerRelativeUrl.TrimEnd('/') + "/" + splistBanners.RootFolder.Url.Trim('/') + "/";

                        foreach (SPListItem banner in banners)
                        {
                            if (banner[PepsiCoColumnId.Banner.Hyperlink] != null && !string.IsNullOrEmpty(banner[PepsiCoColumnId.Banner.Hyperlink].ToString()))
                            {
                                htmlBuilderBanners.AppendFormat("<div><a href='{1}'><img u='image' src='{0}' width='{2}' /></a></div>", bannerListURL + banner.File.Name, banner[PepsiCoColumnId.Banner.Hyperlink].ToString(), tileWidth);
                            }
                            else
                            {
                                htmlBuilderBanners.AppendFormat("<div><img u='image' src='{0}' /></div>", bannerListURL + banner.File.Name);
                            }
                        }
                    }
                }

                if (htmlBuilderBanners.Length <= 0)
                {
                    htmlBuilderBanners.Append("<div>No contents found.</div>");
                }


                //{0}: wideSpell
                //{1}: tallSpell
                //{2}: width
                //{3}: height
                //{4}: banners html
                //{5}: SlideDuration
                //{6}: AutoPlayInterval
                //{7}: PlayOrientation
                //{8}: tileID
                //{9}: tileColor
                htmlBuilder.AppendFormat(@"
<div class='live-tile {0}-wide {1}-tall {9} exclude banner-tile'>
<div>
<script>

    jQuery(document).ready(function ($) {{
        var options{8} = {{
            $AutoPlay: true,                                    //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
            $AutoPlaySteps: 1,                                  //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
            $AutoPlayInterval: {6},                            //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
            $PauseOnHover: 3,                                   //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, default value is 3

            $ArrowKeyNavigation: false,   			            //[Optional] Allows keyboard (arrow key) navigation or not, default value is false
            $SlideEasing: $JssorEasing$.$EaseOutQuint,
            $SlideDuration: {5},                                //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
            $MinDragOffsetToSlide: 20,                          //[Optional] Minimum drag offset to trigger slide , default value is 20
            //$SlideWidth: 600,                                 //[Optional] Width of every slide in pixels, default value is width of 'slides' container
            //$SlideHeight: 300,                                //[Optional] Height of every slide in pixels, default value is height of 'slides' container
            $PlayOrientation: {7},                                //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, default value is 1

            $DirectionNavigatorOptions: {{                       //[Optional] Options to specify and enable direction navigator or not
                $Class: $JssorDirectionNavigator$,              //[Requried] Class to create direction navigator instance
                $ChanceToShow: 1,                               //[Required] 0 Never, 1 Mouse Over, 2 Always
                $AutoCenter: 2,                                 //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                $Steps: 1                                       //[Optional] Steps to go for each navigation request, default value is 1
            }},

            $NavigatorOptions: {{                                //[Optional] Options to specify and enable navigator or not
                $Class: $JssorNavigator$,                       //[Required] Class to create navigator instance
                $ChanceToShow: 2,                               //[Required] 0 Never, 1 Mouse Over, 2 Always
                $AutoCenter: 0,                                 //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                $Steps: 1,                                      //[Optional] Steps to go for each navigation request, default value is 1
                $Lanes: 1,                                      //[Optional] Specify lanes to arrange items, default value is 1
                $SpacingX: 4,                                   //[Optional] Horizontal space between each item in pixel, default value is 0
                $SpacingY: 4,                                   //[Optional] Vertical space between each item in pixel, default value is 0
                $Orientation: 1                                 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
            }}
        }};

        var jssor_slider{8} = new $JssorSlider$('slider{8}_container', options{8});
    }});
</script>

<div id='slider{8}_container' style='position: relative; width: {2}px; height: {3}px; overflow: hidden;'>
    <div u='loading' style='position: absolute; top: 0px; left: 0px;'>
        <div style='filter: alpha(opacity=70); opacity:0.7; position: absolute; display: block;

            background-color: #000; top: 0px; left: 0px;width: 100%; height:100%;'> 
        </div> 
        <div style='position: absolute; display: block; background: url('/Style Library/JssorSlider/img/loading.gif') no-repeat center center;

            top: 0px; left: 0px;width: 100%;height:100%;'>
        </div> 
    </div> 

    <div u='slides' style='cursor: move; position: absolute; left: 0px; top: 0px; width: {2}px; height: {3}px;
        overflow: hidden;'>
{4}
    </div> 

    <style>
        .jssorn03 div, .jssorn03 div:hover, .jssorn03 .av
        {{
            background: url('/Style Library/JssorSlider/img/n03.png') no-repeat;
            overflow:hidden;
            cursor: pointer;
        }}
        .jssorn03 div {{ background-position: -5px -4px; }}
        .jssorn03 div:hover, .jssorn03 .av:hover {{ background-position: -35px -4px; }}
        .jssorn03 .av {{ background-position: -65px -4px; }}
        .jssorn03 .dn, .jssorn03 .dn:hover {{ background-position: -95px -4px; }}
    </style>

    <div u='navigator' class='jssorn03' style='position: absolute; bottom: 16px; left: 6px;'>
        <div u='prototype' style='POSITION: absolute; WIDTH: 21px; HEIGHT: 21px; text-align:center; line-height:21px; color:White; font-size:12px;'><NumberTemplate></NumberTemplate></div>
    </div>

    <style>
        .jssord05l, .jssord05r, .jssord05ldn, .jssord05rdn
        {{
            position: absolute;
            cursor: pointer;
            display: block;
            background: url('/Style Library/JssorSlider/img/d17.png') no-repeat;
            overflow:hidden;
        }}
        .jssord05l {{ background-position: -10px -40px; }}
        .jssord05r {{ background-position: -70px -40px; }}
        .jssord05l:hover {{ background-position: -130px -40px; }}
        .jssord05r:hover {{ background-position: -190px -40px; }}
        .jssord05ldn {{ background-position: -250px -40px; }}
        .jssord05rdn {{ background-position: -310px -40px; }}
    </style>
    <span u='arrowleft' class='jssord05l' style='width: 40px; height: 40px; top: 123px; left: 8px;'>
    </span>
    <span u='arrowright' class='jssord05r' style='width: 40px; height: 40px; top: 123px; right: 8px'>
    </span>
</div>
</div>
</div>
            ", tileWideSpell, tileTallSpell, tileWidth, tileHeight, htmlBuilderBanners.ToString(), dataSpeed, dataDelay, dataDirection, itemTile.ID, tileColor);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl RenderBanners", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return htmlBuilder.ToString();
        }

        protected string RenderNews(SPWeb spWeb, SPListItem itemTile)
        {
            StringBuilder htmlBuilder = new StringBuilder();

            try
            {
                string tileWideSpell = itemTile[PepsiCoColumnId.Tile.TileWide].ToString();
                string tileTallSpell = itemTile[PepsiCoColumnId.Tile.TileTall].ToString();

                //string tileWidth = CalculateTileWideOrTall(tileWideSpell);
                //string tileHeight = CalculateTileWideOrTall(tileTallSpell);

                string tileColor = itemTile[PepsiCoColumnId.Tile.TileColor].ToString();

                string dataMode = itemTile[PepsiCoColumnId.Tile.DataMode].ToString();
                string dataSpeed = itemTile[PepsiCoColumnId.Tile.DataSpeed].ToString();
                string dataDelay = itemTile[PepsiCoColumnId.Tile.DataDelay].ToString();
                string dataPauseOnHover = itemTile[PepsiCoColumnId.Tile.DataPauseOnHover].ToString();
                string dataDirection = itemTile[PepsiCoColumnId.Tile.DataDirection].ToString();

                string showTitle = (itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile] != null && Convert.ToBoolean(itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile])) ? string.Format("<span class='tile-title'>{0}</span>", itemTile[PepsiCoColumnId.Tile.Title].ToString()) : string.Empty;


                uint itemLimit = (itemTile[PepsiCoColumnId.Tile.ItemLimit] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString())) ? uint.Parse(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString()) : 5;

                StringBuilder htmlBuilderNews = new StringBuilder();

                SPList splistNews = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.NEWS_LIST_URL);

                if (splistNews != null)
                {
                    string caml = string.Empty;
                    //var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();

                    caml = Camlex.Query().OrderBy(x => x["Created"] as Camlex.Desc).ToString();
                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;
                    spQuery.RowLimit = itemLimit;

                    SPListItemCollection newses = splistNews.GetItems(spQuery);

                    if (newses != null && newses.Count > 0)
                    {
                        foreach (SPListItem news in newses)
                        {
                            string newsURL = splistNews.DefaultDisplayFormUrl.Substring(0, splistNews.DefaultDisplayFormUrl.LastIndexOf("/")) + "/" + PepsiCoConstants.NEWS_DISPLAYPAGE + ".aspx?Id=" + news.ID;
                            htmlBuilderNews.AppendFormat("<div><a href='{0}' onclick='window.location.href=\"{0}\"'><p style='font-size: 14pt;'>{1}</p><p>{2}</p></a></div>", newsURL, news[SPBuiltInFieldId.Title].ToString(), news["ShortDescription"].ToString().Replace("\n", "<br/>"));
                        }
                    }
                }

                if (htmlBuilderNews.Length <= 0)
                {
                    htmlBuilderNews.Append("<div>No contents found.</div>");
                }

                //{0}: tileWideSpell
                //{1}: tileTallSpell
                //{2}: tileColor
                //{3}: dataMode
                //{4}: dataDirection
                //{5}: dataSpeed
                //{6}: dataDelay
                //{7}: showTitle
                //{8}: HTML content
                htmlBuilder.AppendFormat(@"
<div class='live-tile {0}-wide {1}-tall accent {2}' data-mode='{3}' data-direction='{4}' data-speed='{5}' data-delay='{6}'>
{7}
{8}
</div>
            ", tileWideSpell, tileTallSpell, tileColor, dataMode, dataDirection, dataSpeed, dataDelay, showTitle, htmlBuilderNews.ToString());
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl RenderNews", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return htmlBuilder.ToString();
        }

        protected string RenderContacts(SPWeb spWeb, SPListItem itemTile)
        {
            StringBuilder htmlBuilder = new StringBuilder();

            try
            {
                string tileWideSpell = itemTile[PepsiCoColumnId.Tile.TileWide].ToString();
                string tileTallSpell = itemTile[PepsiCoColumnId.Tile.TileTall].ToString();

                //string tileWidth = CalculateTileWideOrTall(tileWideSpell);
                //string tileHeight = CalculateTileWideOrTall(tileTallSpell);

                string tileColor = itemTile[PepsiCoColumnId.Tile.TileColor].ToString();

                string dataMode = itemTile[PepsiCoColumnId.Tile.DataMode].ToString();
                string dataSpeed = itemTile[PepsiCoColumnId.Tile.DataSpeed].ToString();
                string dataDelay = itemTile[PepsiCoColumnId.Tile.DataDelay].ToString();
                string dataPauseOnHover = itemTile[PepsiCoColumnId.Tile.DataPauseOnHover].ToString();
                string dataDirection = itemTile[PepsiCoColumnId.Tile.DataDirection].ToString();

                string showTitle = (itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile] != null && Convert.ToBoolean(itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile])) ? string.Format("<span class='tile-title'>{0}</span>", itemTile[PepsiCoColumnId.Tile.Title].ToString()) : string.Empty;


                uint itemLimit = (itemTile[PepsiCoColumnId.Tile.ItemLimit] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString())) ? uint.Parse(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString()) : 5;

                StringBuilder htmlBuilderContacts = new StringBuilder();

                SPList splistContacts = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.CONTACT_INFORMATION_LIST_URL);

                if (splistContacts != null)
                {
                    string caml = string.Empty;
                    var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();
                    expressionsAnd.Add(x => ((bool)x["IsActive"]) == true);

                    caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x["Title"] as Camlex.Asc).ToString();
                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;
                    spQuery.RowLimit = itemLimit;

                    SPListItemCollection contacts = splistContacts.GetItems(spQuery);

                    if (contacts != null && contacts.Count > 0)
                    {
                        foreach (SPListItem contact in contacts)
                        {
                            string contactURL = splistContacts.DefaultDisplayFormUrl + "?Id=" + contact.ID;

                            string classHide = "style='display:none'";
                            string classCenter = "style='text-align:center'";

                            string contactImage = string.Empty;
                            if (contact["Thumbnail1"] != null && !string.IsNullOrEmpty(contact["Thumbnail1"].ToString()))
                            {
                                contactImage = string.Format("<img src='{0}' alt='img' width='64'/>", contact["Thumbnail1"].ToString().Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                classHide = string.Empty;
                                classCenter = string.Empty;
                            }

                            string jobTitle = string.Empty;
                            string phone = string.Empty;
                            string desc = string.Empty;

                            if (contact["JobTitle"] != null && !string.IsNullOrEmpty(contact["JobTitle"].ToString()))
                            {
                                jobTitle = string.Format("<div>Job Title: {0}</div>", contact["JobTitle"].ToString());
                            }

                            if (contact["PhoneNumber"] != null && !string.IsNullOrEmpty(contact["PhoneNumber"].ToString()))
                            {
                                phone = string.Format("<div>Phone: {0}</div>", contact["PhoneNumber"].ToString());
                            }

                            if (contact["ShortDescription"] != null && !string.IsNullOrEmpty(contact["ShortDescription"].ToString()))
                            {
                                desc = string.Format("<div>{0}</div>", contact["ShortDescription"].ToString().Replace("\n", "<br/>"));
                            }


                            //{0}: link view
                            //{1}: is Hide ?
                            //{2}: image
                            //{3}: name
                            //{4}: job title
                            //{5}: phone
                            //{6}: desc
                            htmlBuilderContacts.AppendFormat("<div><a href='{0}' onclick='window.location.href=\"{0}\"'><table width='100%' border='0' height='80%'><tbody><tr><td width='80px' align='center' valign='middle' {1}>{2}</td><td width='*' valign='middle'><div class='pmetro-title' {7}>{3}</div>{4}{5}{6}</td></tr></tbody></table></a></div>",
                                contactURL, classHide, contactImage, contact[SPBuiltInFieldId.Title].ToString(), jobTitle, phone, desc, classCenter);
                        }
                    }
                }

                if (htmlBuilderContacts.Length <= 0)
                {
                    htmlBuilderContacts.Append("<div>No contents found.</div>");
                }

                //{0}: tileWideSpell
                //{1}: tileTallSpell
                //{2}: tileColor
                //{3}: dataMode
                //{4}: dataDirection
                //{5}: dataSpeed
                //{6}: dataDelay
                //{7}: showTitle
                //{8}: HTML content
                htmlBuilder.AppendFormat(@"
<div class='live-tile {0}-wide {1}-tall accent {2}' data-mode='{3}' data-direction='{4}' data-speed='{5}' data-delay='{6}'>
{7}
{8}
</div>
            ", tileWideSpell, tileTallSpell, tileColor, dataMode, dataDirection, dataSpeed, dataDelay, showTitle, htmlBuilderContacts.ToString());
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl RenderContacts", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return htmlBuilder.ToString();
        }

        protected string RenderServicesAndTools(SPWeb spWeb, SPListItem itemTile)
        {
            StringBuilder htmlBuilder = new StringBuilder();

            try
            {
                string tileWideSpell = itemTile[PepsiCoColumnId.Tile.TileWide].ToString();
                string tileTallSpell = itemTile[PepsiCoColumnId.Tile.TileTall].ToString();

                //string tileWidth = CalculateTileWideOrTall(tileWideSpell);
                //string tileHeight = CalculateTileWideOrTall(tileTallSpell);

                string tileColor = itemTile[PepsiCoColumnId.Tile.TileColor].ToString();

                string dataMode = itemTile[PepsiCoColumnId.Tile.DataMode].ToString();
                string dataSpeed = itemTile[PepsiCoColumnId.Tile.DataSpeed].ToString();
                string dataDelay = itemTile[PepsiCoColumnId.Tile.DataDelay].ToString();
                string dataPauseOnHover = itemTile[PepsiCoColumnId.Tile.DataPauseOnHover].ToString();
                string dataDirection = itemTile[PepsiCoColumnId.Tile.DataDirection].ToString();

                string showTitle = (itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile] != null && Convert.ToBoolean(itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile])) ? string.Format("<span class='tile-title'>{0}</span>", itemTile[PepsiCoColumnId.Tile.Title].ToString()) : string.Empty;


                uint itemLimit = (itemTile[PepsiCoColumnId.Tile.ItemLimit] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString())) ? uint.Parse(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString()) : 5;

                StringBuilder htmlBuilderLinks = new StringBuilder();

                SPList splistLinks = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.LINKS_LIST_URL);

                if (splistLinks != null)
                {
                    string caml = string.Empty;
                    var expressionsAnd = new List<Expression<Func<SPListItem, bool>>>();
                    expressionsAnd.Add(x => ((bool)x["IsActive"]) == true);

                    caml = Camlex.Query().WhereAll(expressionsAnd).OrderBy(x => x["Title"] as Camlex.Asc).ToString();
                    SPQuery spQuery = new SPQuery();
                    spQuery.Query = caml;
                    spQuery.RowLimit = itemLimit;

                    SPListItemCollection links = splistLinks.GetItems(spQuery);

                    if (links != null && links.Count > 0)
                    {
                        foreach (SPListItem link in links)
                        {
                            string linkURL = string.Empty;
                            if (link["Links"] != null && !string.IsNullOrEmpty(link["Links"].ToString()))
                            {
                                SPFieldUrlValue spfieldHyperlink = new SPFieldUrlValue(link["Links"].ToString());

                                linkURL = spfieldHyperlink.Url;
                            }

                            string classHide = "style='display:none'";
                            string classCenter = "style='text-align:center'";

                            string linkImage = string.Empty;
                            if (link["Thumbnail1"] != null && !string.IsNullOrEmpty(link["Thumbnail1"].ToString()))
                            {
                                linkImage = string.Format("<img src='{0}' alt='img' width='64'/>", link["Thumbnail1"].ToString().Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                                classHide = string.Empty;
                                classCenter = string.Empty;
                            }

                            string desc = string.Empty;

                            if (link["ShortDescription"] != null && !string.IsNullOrEmpty(link["ShortDescription"].ToString()))
                            {
                                desc = string.Format("<div>{0}</div>", link["ShortDescription"].ToString().Replace("\n", "<br/>"));
                            }


                            //{0}: link
                            //{1}: is Hide ?
                            //{2}: image
                            //{3}: name
                            //{4}: desc
                            htmlBuilderLinks.AppendFormat("<div><a href='{0}' onclick='window.location.href=\"{0}\"'><table width='100%' border='0' height='80%'><tbody><tr><td width='80px' align='center' valign='middle' {1}>{2}</td><td width='*' valign='middle'><div class='pmetro-title' {5}>{3}</div>{4}</td></tr></tbody></table></a></div>",
                                linkURL, classHide, linkImage, link[SPBuiltInFieldId.Title].ToString(), desc, classCenter);
                        }
                    }
                }

                if (htmlBuilderLinks.Length <= 0)
                {
                    htmlBuilderLinks.Append("<div>No contents found.</div>");
                }

                //{0}: tileWideSpell
                //{1}: tileTallSpell
                //{2}: tileColor
                //{3}: dataMode
                //{4}: dataDirection
                //{5}: dataSpeed
                //{6}: dataDelay
                //{7}: showTitle
                //{8}: HTML content
                htmlBuilder.AppendFormat(@"
<div class='live-tile {0}-wide {1}-tall accent {2}' data-mode='{3}' data-direction='{4}' data-speed='{5}' data-delay='{6}'>
{7}
{8}
</div>
            ", tileWideSpell, tileTallSpell, tileColor, dataMode, dataDirection, dataSpeed, dataDelay, showTitle, htmlBuilderLinks.ToString());
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl RenderServicesAndTools", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return htmlBuilder.ToString();
        }

        protected string RenderCustomContent(SPWeb spWeb, SPListItem itemTile)
        {
            StringBuilder htmlBuilder = new StringBuilder();

            try
            {
                string tileWideSpell = itemTile[PepsiCoColumnId.Tile.TileWide].ToString();
                string tileTallSpell = itemTile[PepsiCoColumnId.Tile.TileTall].ToString();

                //string tileWidth = CalculateTileWideOrTall(tileWideSpell);
                //string tileHeight = CalculateTileWideOrTall(tileTallSpell);

                string tileColor = itemTile[PepsiCoColumnId.Tile.TileColor].ToString();

                string dataMode = itemTile[PepsiCoColumnId.Tile.DataMode].ToString();
                string dataSpeed = itemTile[PepsiCoColumnId.Tile.DataSpeed].ToString();
                string dataDelay = itemTile[PepsiCoColumnId.Tile.DataDelay].ToString();
                string dataPauseOnHover = itemTile[PepsiCoColumnId.Tile.DataPauseOnHover].ToString();
                string dataDirection = itemTile[PepsiCoColumnId.Tile.DataDirection].ToString();

                string showTitle = (itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile] != null && Convert.ToBoolean(itemTile[PepsiCoColumnId.Tile.ShowTitleOnTile])) ? string.Format("<span class='tile-title'>{0}</span>", itemTile[PepsiCoColumnId.Tile.Title].ToString()) : string.Empty;


                //uint itemLimit = (itemTile[PepsiCoColumnId.Tile.ItemLimit] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString())) ? uint.Parse(itemTile[PepsiCoColumnId.Tile.ItemLimit].ToString()) : 5;

                StringBuilder htmlBuilderLinks = new StringBuilder();

                string linkURL = string.Empty;
                if (itemTile[PepsiCoColumnId.Tile.Hyperlink] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.Hyperlink].ToString()))
                {
                    SPFieldUrlValue spfieldHyperlink = new SPFieldUrlValue(itemTile[PepsiCoColumnId.Tile.Hyperlink].ToString());

                    linkURL = spfieldHyperlink.Url;
                }

                string classHide = "style='display:none'";
                string classCenter = "style='text-align:center'";

                string linkImage = string.Empty;
                if (itemTile[PepsiCoColumnId.Tile.Thumbnail1] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.Thumbnail1].ToString()))
                {
                    linkImage = string.Format("<img src='{0}' alt='img' width='64'/>", itemTile[PepsiCoColumnId.Tile.Thumbnail1].ToString().Split(new string[] { ";#" }, StringSplitOptions.None)[1]);
                    classHide = string.Empty;
                    classCenter = string.Empty;
                }

                string desc = string.Empty;

                if (itemTile[PepsiCoColumnId.Tile.Contents] != null && !string.IsNullOrEmpty(itemTile[PepsiCoColumnId.Tile.Contents].ToString()))
                {
                    desc = string.Format("<div>{0}</div>", itemTile[PepsiCoColumnId.Tile.Contents].ToString().Trim());
                }



                if (!string.IsNullOrEmpty(linkURL))
                {
                    //{0}: link
                    //{1}: is Hide ?
                    //{2}: image
                    //{3}: desc
                    htmlBuilderLinks.AppendFormat("<div><a href='{0}' onclick='window.location.href=\"{0}\"'><table width='100%' border='0' height='80%'><tbody><tr><td width='80px' align='center' valign='middle' {1}>{2}</td><td width='*' valign='middle'>{3}</td></tr></tbody></table></a></div>",
                        linkURL, classHide, linkImage, desc);
                }
                else
                {
                    //{0}: is Hide ?
                    //{1}: image
                    //{2}: desc
                    htmlBuilderLinks.AppendFormat("<div><table width='100%' border='0' height='80%'><tbody><tr><td width='80px' align='center' valign='middle' {0}>{1}</td><td width='*' valign='middle'>{2}</td></tr></tbody></table></div>",
                        classHide, linkImage, desc);
                }



                //{0}: tileWideSpell
                //{1}: tileTallSpell
                //{2}: tileColor
                //{3}: dataMode
                //{4}: dataDirection
                //{5}: dataSpeed
                //{6}: dataDelay
                //{7}: showTitle
                //{8}: HTML content
                htmlBuilder.AppendFormat(@"
<div class='live-tile {0}-wide {1}-tall accent {2} exclude' data-mode='{3}' data-direction='{4}' data-speed='{5}' data-delay='{6}'>
{7}
{8}
</div>
            ", tileWideSpell, tileTallSpell, tileColor, dataMode, dataDirection, dataSpeed, dataDelay, showTitle, htmlBuilderLinks.ToString());
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ModernUIUserControl RenderCustomContent", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return htmlBuilder.ToString();
        }

        protected string CalculateTileWideOrTall(string value)
        {
            int result = 150; //default

            int num = 0;

            switch (value)
            {
                case "half":
                    result = 70;
                    break;
                case "one":
                    num = 1;
                    break;
                case "two":
                    num = 2;
                    break;
                case "three":
                    num = 3;
                    break;
                case "four":
                    num = 4;
                    break;
                case "five":
                    num = 5;
                    break;
                case "six":
                    num = 6;
                    break;
                case "seven":
                    num = 7;
                    break;
                case "eight":
                    num = 8;
                    break;
                case "nine":
                    num = 9;
                    break;
                case "ten":
                    num = 10;
                    break;
            }

            if (num > 0)
            {
                result = (150 * num) + ((num - 1) * 10);
            }

            return result.ToString();
        }
    }
}
